import express, { Express, Request, Response, Router } from "express";
const { db } = require("../db/dbUntil")


const router: Router = express.Router()
router.get("/list", async (req: Request, res: Response) => {
    let sql = "select * from `messages`"
    const { err, rows } = await db.async.all(sql, [])
    res.send({
        code: 200,
        data: rows
    })
})

//添加评论
router.post("/add", async (req: Request, res: Response) => {
    let { comment } = req.body;
    console.log(comment);

    let sql = "insert into `messages` (`comment`,`date`) values (?,?)"
    let date=new Date().toLocaleString();    

    const { err, rows } = await db.async.run(sql, [comment, date])

    if (err == null) {
        res.send({
            code: 200,
            msg: "添加成功"
        })
    } else {
        console.log(err);
        res.send({
            code: 500,
            msg: err
        })
    }
})


//回复
router.put("/update",async (req:Request,res:Response)=>{
    let { id,answer } = req.body;

    let sql="update `messages` SET `answer` = ? where `id` = ?"

    const { err, rows } =  await db.async.run(sql,[answer,id])

    if (err == null) {
        res.send({
            code: 200,
            msg: "修改成功"
        })
    } else {
        console.log(err);
        res.send({
            code: 500,
            msg: err
        })
    }
})

//删除
router.delete("/delete",async(req:Request,res:Response)=>{
    let id = req.query.id
    const sql = "delete from `messages` where `id` = ?"
    let { err, rows } = await db.async.run(sql, [id])

    if (err == null) {
        res.send({
            code: 200,
            msg: "删除成功"
        })
    } else {
        res.send({
            code: 500,
            msg: err
        })
    }

})


module.exports = router